package config

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
	"ug-uploads/logx"

	"go.uber.org/zap"
)

type Config struct {
	BaseURL       string   `json:"BaseURL"`
	DBPath        string   `json:"DBPath"`
	// AccessToken   string   `json:"AccessToken"`
	AdvertiserIDs []string `json:"AdvertiserIDs"`

	TOSEndpoint string `json:"TOSEndpoint"`
	TOSRegion   string `json:"TOSRegion"`
	BucketName  string `json:"BucketName"`
	AccessKey   string `json:"AccessKey"`
	SecretKey   string `json:"SecretKey"`

	User         string        `json:"User"`
	Password     string        `json:"Password"`
	Host         string        `json:"Host"`
	Port         int           `json:"Port"`
	DBName       string        `json:"DBName"`
	MaxOpenConns int           `json:"MaxOpenConns"`
	MaxIdleConns int           `json:"MaxIdleConns"`
	MaxLifetime  time.Duration `json:"MaxLifetime"`

	CreatePkgURL   string `json:"CreatePkgURL"`
	AddMaterialURL string `json:"AddMaterialURL"`
}

var (
	Cfg     Config
	onceCfg sync.Once
)

func Init() error {
	var initErr error
	onceCfg.Do(func() {
		file, err := os.Open("config.json")

		if err != nil {
			initErr = fmt.Errorf("打开配置文件失败: %v", err)
			return
		}

		defer file.Close()

		data, err := io.ReadAll(file)

		if err != nil {
			initErr = fmt.Errorf("读取配置文件失败: %v", err)
			return
		}

		if err := json.Unmarshal(data, &Cfg); err != nil {
			initErr = fmt.Errorf("解析配置文件失败: %v", err)
			return
		}

		if Cfg.MaxLifetime < time.Minute {
			Cfg.MaxLifetime = Cfg.MaxLifetime * time.Second
		}

		if len(Cfg.AdvertiserIDs) == 0 {
			initErr = fmt.Errorf("请在 config.json 中添加广告主 ID")
			return
		}

		// if Cfg.AccessToken == "" {
		// 	Cfg.AccessToken = getAccessToken()
		// }

		logx.Logger.Info("配置系统初始化完成", zap.String("config_file", "./config.json"))

	})

	if initErr != nil {
		return initErr
	}

	return nil
}

func GetAccessToken() string {
	reqBody := `{"accountId":"1844654898452480"}`
	req, err := http.NewRequest("POST", "https://optapi.gghys.com/service-api/oceanengine/accounts/access-token", strings.NewReader(reqBody))
	if err != nil {
		log.Fatalf("创建AccessToken请求失败: %v", err)
	}
	req.Header.Set("x-service-key", "gFnGn~58Hk^dF(+uEtc+cish")
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalf("请求AccessToken失败: %v", err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)

	var data map[string]any
	if err := json.Unmarshal(body, &data); err != nil {
		log.Fatalf("解析AccessToken失败: %v", err)
	}
	token := data["data"].(string)
	// log.Printf("AccessToken 获取成功: %s", token)
	return token
}
